import os
import re
from datetime import datetime
import csv


def parse_filename(filename):
    """解析使用双下划线分隔的文件名"""
    # 移除文件扩展名
    base_name = os.path.splitext(filename)[0]

    # 使用双下划线分割文件名
    parts = base_name.split('__')

    # 检查是否有足够的字段
    if len(parts) < 4:
        return None

    # 提取各字段
    system_name = parts[0]
    switch_model = parts[1]
    ip_address = parts[2]
    timestamp = parts[3]

    # 验证IP地址格式
    if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip_address):
        return None

    # 解析时间戳
    try:
        # 处理时间戳中的下划线（日期和时间之间）
        if '_' in timestamp:
            date_part, time_part = timestamp.split('_')
        else:
            date_part = timestamp[:8]
            time_part = timestamp[8:]

        # 格式化时间
        extract_time = datetime.strptime(f"{date_part}{time_part}", "%Y%m%d%H%M%S")
        formatted_time = extract_time.strftime("%Y-%m-%d %H:%M:%S")
    except ValueError:
        formatted_time = timestamp  # 如果无法解析，保留原始时间戳

    return {
        "系统名称": system_name,
        "交换机型号": switch_model,
        "IP地址": ip_address,
        "提取时间": formatted_time
    }


def process_directory(directory):
    """处理目录中的所有cfg文件"""
    results = []

    for filename in os.listdir(directory):
        if filename.endswith('.cfg'):
            parsed = parse_filename(filename)
            if parsed:
                results.append(parsed)
                print(f"文件名: {filename}")
                for key, value in parsed.items():
                    print(f"  {key}: {value}")
                print()
            else:
                print(f"无法解析文件名: {filename}\n")

    return results


def save_to_csv(results, output_file):
    """将结果保存为CSV文件"""
    with open(output_file, 'w', newline='', encoding='utf-8-sig') as csvfile:
        fieldnames = ['系统名称', '交换机型号', 'IP地址', '提取时间']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()
        for result in results:
            writer.writerow(result)

    print(f"结果已保存到 {output_file}")


if __name__ == "__main__":
    # 设置工作目录
    directory = '.'  # 当前目录
    output_file = 'switch_info.csv'

    # 处理目录中的所有cfg文件
    results = process_directory(directory)

    # 保存结果到CSV
    save_to_csv(results, output_file)